<template>
  <div class="editPurchasePrice" @click.stop="aotuTab=false">
    <div style="display: flex" class="header">
      <jc-button
        :btn-arr="['reload', 'pass', 'save', 'sub', 'ward', 'remove', 'option', 'list', 'disagree']"
        :disab-arr="[isDisabled && 'save', 'close', 'cancel', 'toExcel', 'freeze']"
        :list="'/purchasePriceList'"
        @save="preservation"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @disagree="audit(3)"
        @submit="preservation(1)"
        @noSubmit="submit(2)"
        @refresh="queryTPurPriceList"
        @del="editPurchase"
        @startUsing="using(1)"
        @forbidden="using(2)"
        @forward="forward(1)"
        @handleCom1="queryReportForm1(1)"
        @handleCom2="queryReportForm1(2)"
      />
      <el-button style="margin-left: 10px;" size="mini" type="success" @click="forward(2)">{{ $t('market.forwardCom') }}</el-button>
      <el-button style="margin-left: 10px" size="mini" type="primary" @click="pushView">{{ $t('market.backApprove') }}</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="purchase" class="layout">
        <el-form
          ref="purchaseRef"
          :model="purchaseForm"
          label-width="100px"
          size="mini"
        >
          <el-form-item :label="$t('market.documentstatus')">
            <el-tag :type="purchaseForm.stateColor">{{ purchaseForm.fdocumentStatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.supplier')" prop="fsupplier">
            <el-input
              v-model="purchaseForm.fsupplier"
              class="input-width"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('shop.name1')" prop="fname">
            <el-input
              v-model="purchaseForm.fname"
              class="input-width"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item :label="$t('market.billNo')" prop="code">
            <el-input
              v-model="purchaseForm.code"
              class="input-width"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.currency2')" prop="fcurrency">
            <el-input
              v-model="purchaseForm.fcurrency"
              class="input-width"
              disabled
            >
              <i slot="suffix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.supplierRate')" prop="fpaezBase">
            <el-input
              v-model.trim="purchaseForm.fpaezBaseName"
              size="mini"
              class="input-width"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.pricetype')" prop="fpriceType">
            <el-select
              v-model="purchaseForm.fpriceType"
              class="input-width"
              :disabled="isDisabled"
            >
              <el-option
                v-for="option in priceTypeList"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.tax')" prop="fisIncludedTax">
            <el-checkbox
              v-model="purchaseForm.fisIncludedTax"
              class="input-width"
              :disabled="isDisabled"
              @change="handleTax"
            />
          </el-form-item>
          <el-form-item :label="$t('market.paymentClause')">
            <el-input
              v-model="purchaseForm.fpaycondition"
              :disabled="isDisabled"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.note')" prop="fnote">
            <el-input
              v-model="purchaseForm.fnote"
              :disabled="isDisabled"
              class="input-width"
            />
          </el-form-item>
        </el-form>
        <div class="header-name">
          <el-button class="newBtn" size="mini" @click="newLine">
            {{ $t('btn.newHang') }}
          </el-button>
          <el-button class="newBtn" size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button class="newBtn" size="mini" :disabled="isDisabled" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
          <search
            :options="selectData"
            :msg="tacitly"
            @seek="collect"
            @hand="queryTPurPriceList"
          />
          <el-button
            type="primary"
            class="btn"
            size="mini"
            @click="queryTPurPriceList"
          >
            {{ $t('btn.search') }}
          </el-button>
        </div>
        <div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            :table-height="tableHeight"
            serial
            @rowClick="rowClick"
            @cellClick="cellClick"
          >
            <el-table-column
              v-if="msg"
              :label="$t('market.fmaterial')"
              prop="fnumber"
              align="center"
              width="160px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  size="mini"
                  :disabled="isDisabled"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i
                    slot="prefix"
                    class="iconfont icon-jin-rud-ao-bo"
                    @click="sonJump(scope.row.fnumber)"
                  />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handleGetMateriel(scope.row, scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && tableIndex === scope.$index" :class="tableIndex<7 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber1" :bom-code="bomCode" @material="materielSelectRow" />
                </div>
              </template>
            </el-table-column>
            <!--跳转物料详情页面不同-->
            <el-table-column
              v-if="!msg"
              :label="$t('market.fmaterial')"
              prop="fnumber"
              align="center"
              width="160px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  size="mini"
                  :disabled="isDisabled"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i
                    slot="prefix"
                    class="iconfont icon-jin-rud-ao-bo"
                    @click="jumpMateriel(scope.row.fnumber, scope.row.fisdefault)"
                  />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handleGetMateriel(scope.row, scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && tableIndex === scope.$index" :class="tableIndex<7 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber1" @material="materielSelectRow" />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('shop.fname2')"
              prop="fname"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              :label="$t('shop.fmodel')"
              prop="fmodel"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              :label="$t('shop.fspecificaTion')"
              prop="fspecificaTion"
              align="center"
              width="120"
            />
            <el-table-column
              :label="$t('market.fdescripTion')"
              prop="fdescripTion"
              align="center"
              min-width="200px"
              :show-overflow-tooltip="true"
            />
            <el-table-column :label="$t('market.chargeunit')" prop="funit" align="center" width="80" />
            <el-table-column
              :label="$t('market.fprice')"
              prop="fprice"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fprice"
                  size="mini"
                  :disabled="fpriceDisabled || isDisabled"
                  :step="0.01"
                  :min="0"
                  :precision="4"
                  @change="handleUnitPrice(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.ftaxPrice')"
              prop="ftaxPrice"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model.number="scope.row.ftaxPrice"
                  size="mini"
                  :disabled="ftaxPriceDisabled || isDisabled"
                  :step="0.01"
                  :min="0"
                  :precision="4"
                  @change="handleTaxIncluded(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.effectiveDate')"
              prop="feffectiveDate"
              align="center"
              min-width="120px"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.feffectiveDate"
                  size="mini"
                  type="date"
                  value-format="yyyy-MM-dd"
                  style="width: 150px"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.expiryDate')"
              prop="fexpiryDate"
              align="center"
              min-width="120px"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.fexpiryDate"
                  size="mini"
                  :disabled="isDisabled"
                  type="date"
                  style="width: 150px"
                  value-format="yyyy-MM-dd"
                />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.ftaxRate')"
              prop="ftaxRate"
              align="center"
              width="80"
            >
              <!--              <template slot-scope="scope">-->
              <!--                <el-input-number-->
              <!--                  v-model.number="scope.row.ftaxRate"-->
              <!--                  size="mini"-->
              <!--                  :min="0"-->
              <!--                  :disabled="isDisabled"-->
              <!--                  @change="handleTaxRate(scope.row)"-->
              <!--                />-->
              <!--              </template>-->
            </el-table-column>
            <template v-slot:text2Slot="col">
              <el-input v-model="col.scope.row.fnote" size="mini" :disabled="isDisabled" />
            </template>
            <template v-slot:btnSlot="clo">
              <el-button
                type="danger"
                size="mini"
                :disabled="isDisabled"
                @click="deleteMateriel(clo.scope.$index)"
              >
                {{ $t('shop.delete') }}
              </el-button>
            </template>
          </jc-table>
          <jc-pagination
            :total="total"
            :page.sync="pageNum"
            :limit.sync="pageSize"
            @pagination="queryTPurPriceList"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="purchaseForm.code"
          other-height="68vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-dialogDrag
      :title="$t('market.approveNote')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <span>{{ $t('market.approveNote') }}</span>
      <el-input v-model="remarks" type="textarea" />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <!--转发-->
    <el-dialog
      v-dialogDrag
      :title="forwardTitle"
      model
      :visible.sync="iswardDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div v-if="confir === 1" style="height: 30px;line-height: 30px">
        {{ $t('market.forwarder') }}
        <el-select v-model="fstaffid">
          <el-option v-for="item in userList" :key="item.fstaffid" :label="item.fstaff" :value="item.fstaffid" />
        </el-select>
      </div>
      <div style="height: 30px;line-height: 30px">{{ $t('market.approveNote') }}</div>
      <el-input v-model="remarks1" type="textarea" />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="iswardDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="forwardConfirm()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <!--    物料弹窗-->
    <material v-if="openMaterialDialog" @material="materielSelectRow" />
    <!--  审批详情  -->
    <appDetails v-if="isAppDetails" :table-data2="tableData2" @close="isAppDetails=false" />
  </div>
</template>

<script>
import {
  deletePur,
  deletePurPriceDetails,
  detailPriceList,
  disablePur,
  forwardConfirmTPurPrice,
  forwardTPurPrice,
  purAudit,
  purAuSubmit,
  purSubmit,
  purUnAudit, queryForwardTPurPrice,
  undisablePur
} from '@/api/purchaseManagement/purchasePrice'
import {
  updatePurPrice
} from '@/api/purchaseManagement/createPurchasePrice'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina } from '@/components/ToMxamineState'
import {
  queryTPurPriceList
} from '@/api/purchaseManagement/refusePriceList'
import { maxDecimal } from '@/utils/number'
import jcButton from '@/components/Button'
import jcMarker from '@/components/marker'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import { purAuditUnApproval } from '@/api/purchaseManagement/purchaseOrder'
import Bus from '@/utils/bus'

export default {
  name: 'EditPurchasePrice',
  components: {
    jcButton,
    jcMarker,
    search,
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    appDetails: () => import('@/views/purchasing/modifyPrice/components/appDetails'),
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [searData, autocomplete],
  props: {
    msg: {
      type: [Number, String],
      default: ''
    },
    fmater: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    return {
      remarks1: '',
      userList: [],
      fstaffid: '',
      confir: 1,
      forwardTitle: '',
      iswardDialog: false,
      isdanjuDialog: false,
      remarks: '',
      ftype: 0,
      fbillNo: 'fnumber', // 编码
      activeName: 'purchase', // 默认在采购
      tableData: [], // 采购价目表
      aotuTab: false,
      isDisabled: false,
      fnumber1: '',
      bomCode: '1',
      tableHeight: 'calc(100vh - 330px)',
      tableHeader: [
        {
          label: this.$t('market.topPrice'),
          prop: 'fupprice',
          width: '80'
        },
        {
          label: this.$t('market.downPrice'),
          prop: 'fdownprice',
          width: '80'
        },
        { label: this.$t('market.note'), prop: 'fnote', type: 'text2', width: '120' },
        { label: this.$t('market.fstoreunit'), prop: 'fstoreunit', width: '80' },
        { label: this.$t('market.fstorePrice'), prop: 'fstorePrice', width: '90' },
        {
          label: this.$t('market.handle'),
          type: 'btn',
          fixed: 'right',
          minWidth: '80px'
        }
      ],
      materielDialogData: [],
      materielDialogHeader: [
        { label: this.$t('market.fmaterial'), prop: 'FNUMBER' },
        { label: this.$t('shop.fspecificaTion'), prop: 'FSPECIFICATION' },
        { label: this.$t('market.chargeunit'), prop: 'FVOLUMEUNIT' },
        { label: this.$t('market.fmodel'), prop: 'FMODEL' },
        {
          label: this.$t('market.descrip'),
          prop: 'FDESCRIPTION',
          minWidth: '150px'
        },
        { label: this.$t('market.createDate'), prop: 'FCREATEDATE' }
      ],
      // 物料弹窗分页
      materielPagination: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        pageSize: 20 // 每页显示多少条数据
      },
      priceTypeList: [], // 价格类型
      ftaxRate: 0, // 税率
      openMaterialDialog: false, // 物料弹窗
      FNUMBER: '', // 弹窗编码
      selectAll: [], // 全选数据
      FDESCRIPTION: '', // 弹窗描述
      FSPECIFICATION: '', // 弹窗物料规格
      fpriceDisabled: true, // 单价禁用
      ftaxPriceDisabled: false, // 含税单价禁用
      // 点击行的序号
      tableIndex: 0,
      otherUrlObject: {}, // 其它审核人
      // 采购价目表头
      purchaseForm: {
        fid: '', // 价目表ID
        fpriceType: '', // 价格类型值
        fpaezBase: '', // 供应商税率
        fsupplier: '', // 供应商名称
        fcurrency: '', // 币别名称
        code: '', // 编码
        fname: '', // 名称
        fisIncludedTax: false, // 含税
        fdescripTion: '' // 描述
      },
      pageNum: 1,
      pageSize: 20,
      total: 20,
      isAppDetails: false,
      tableData2: [],
      delArr: [], // 删除的价目id
      fnumber: '',
      fdescripTion: '',
      matRow: true,
      fidShow: 0 // 审核按钮 0显示，1不显示
    }
  },
  watch: {
    msg() {
      if (this.msg) {
        this.fidShow = 1
        this.searCollData.fnumber = ''
        this.getPriceList(this.msg)
      }
    },
    fmater() {
      if (this.fmater) {
        this.matRow = true
        this.fidShow = 1
        // 判断是否有重复
        this.tableData.forEach(item => {
          if (item.fmaterialId === this.fmater) {
            this.matRow = false
            return
          }
        })
        if (this.matRow) {
          this.materielSelectRow(this.fmater)
        }
      }
    }
  },
  created() {
    this.getPriceList(this.msg)
    this.handleGetPriceType()
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber1 = fnumber
      }, 1000)
    },
    // 复制
    copyData() {
      const data = {
        id: this.$route.params.id || this.msg,
        fname: this.purchaseForm.fname
      }
      this.$emit('copy', data)
    },
    // 新增物料 新增调价
    bomType(ev) {
      this.$emit('mater', ev)
    },
    // 物料详情
    sonJump(ev) {
      this.$emit('mater', ev)
    },
    // 修改价目跳转新增物料(不是树形供应商跳转)
    createType() {
      this.$router.push('/createMateriel')
    },
    pushView() {
      this.$router.push('/purApproveList')
    },
    // 打开转发弹窗
    forward(ev) {
      this.iswardDialog = true
      this.confir = ev
      this.remarks1 = ''
      this.fstaffid = ''
      ev === 1 ? this.forwardTitle = this.$t('market.forward') : this.forwardTitle = this.$t('market.forwardCom')
      ev === 1 && this.queryForwards()
    },
    // 转发人
    queryForwards() {
      const DATA = {
        Numbers: [this.purchaseForm.code]
      }
      queryForwardTPurPrice(DATA).then(res => {
        if (res.code === 0) {
          this.userList = res.data
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 转发
    forwardConfirm() {
      const DATA = {
        Numbers: [this.purchaseForm.code],
        fstaffid: this.fstaffid,
        remarks: this.remarks1
      }
      const api = this.confir === 1 ? forwardTPurPrice : forwardConfirmTPurPrice
      api(DATA).then(res => {
        if (res.code === 0) {
          this.iswardDialog = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 获取数据
    async getPriceList(ev) {
      const fid = this.$route.params.id || ev
      const DATA = {
        fid: fid
      }
      if (fid) {
        const { data: RES, code, message } = await detailPriceList(DATA)
        if (code === 0) {
          this.otherUrlObject = RES // 其他
          const { fisIncludedTax, fnumber } = RES
          this.purchaseForm = toMxAmina(RES)
          this.purchaseForm.code = fnumber
          this.isDisabled = this.purchaseForm.fdocumentStatus === this.$t('market.state1') || this.purchaseForm.fdocumentStatus === this.$t('market.state2')
          if (fisIncludedTax) {
            this.fpriceDisabled = true
            this.ftaxPriceDisabled = false
            this.purchaseForm.fisIncludedTax = true
          } else {
            this.fpriceDisabled = false
            this.ftaxPriceDisabled = true
            this.purchaseForm.fisIncludedTax = false
          }
          // this.tableData = detail
          this.queryTPurPriceList()
        } else {
          this.$message.error(message)
        }
      }
    },
    // 价目表数据
    async queryTPurPriceList() {
      const fid = this.$route.params.id || this.msg
      const DATA = {
        fid: fid,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        search: this.searCollData
      }
      await queryTPurPriceList(DATA).then(res => {
        if (res.code === 0) {
          this.tableData = res.data.detail
          this.total = res.data.total
          this.tableData2 = res.data.approvalRemarks
          this.isAppDetails = res.data.approvalRemarks?.length > 0
          this.ftaxRate = this.tableData[0].ftaxRate
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 获取价格类型
    async handleGetPriceType() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_PRICETYPE' })
      this.priceTypeList = RES.list.map(item => {
        const { fname: label, fid: value } = item
        return { label, value }
      })
    },
    // 保存采购列表
    preservation(ev) {
      if (this.purchaseForm.ftaxRate !== 0) {
        for (const item in this.tableData) {
          const ITEM = this.tableData[item]
          if (
            !ITEM.fmaterialId ||
              ITEM.fprice === 0 ||
              ITEM.ftaxPrice === 0
          ) {
            if (ITEM.fprice === 0) {
              this.cont = '单价'
            } else if (ITEM.ftaxPrice === 0) {
              this.cont = '含税单价'
            }
            this.$message.warning(
              '第' + Number(Number(item) + Number(1)) + '行表格,' + this.cont + '不能为空,或表格值不能为0'
            )
            return
          }
        }
      }
      const DETAILS = this.tableData.map(item => {
        const {
          fnote,
          fmaterialId,
          fprice,
          ftaxPrice,
          fupprice,
          fdownprice,
          ftaxRate,
          fentryId,
          fexpiryDate,
          feffectiveDate,
          funitId
        } = item
        return {
          fnote,
          fmaterialId,
          fprice,
          ftaxPrice,
          fentryId,
          fexpiryDate,
          fupPrice: fupprice,
          fdownPrice: fdownprice,
          ftaxRate,
          feffectiveDate: feffectiveDate,
          funitId
        }
      })
      const { fid, fname, fisIncludedTax, fnote, fpaezBase, fpriceType } = this.purchaseForm
      const DATA = {
        fid,
        fname,
        fisIncludedTax: fisIncludedTax ? 1 : 0,
        fnote,
        fpaezBase,
        fpriceType,
        details: DETAILS,
        delArr: this.delArr
      }
      updatePurPrice(DATA)
        .then(res => {
          if (res.code !== 0) {
            this.$message({ showClose: true, message: res.message, type: 'error' })
            return
          }
          this.delArr = []
          this.$message({ showClose: true, message: res.message, type: 'success' })
          ev === 1 ? this.submit(1) : this.getPriceList(this.msg)
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 物料弹窗选中
    async materielSelectRow(ev) {
      // if (this.fmater) {
      //   this.tableIndex = this.tableData.length
      //   this.tableData.push({
      //     fmaterialId: FMATERIALID, // 物料编码
      //     fnumber: FNUMBER,
      //     fprice: 0, // 单价
      //     ftaxPrice: 0, // 含税单价
      //     fupprice: 0, // 价格上限
      //     fdownprice: 0, // 价格下限
      //     feffectiveDate: new Date(), // 生效时间
      //     ftaxRate: this.ftaxRate, // 税率
      //     fdescripTion: FDESCRIPTION, // 描述
      //     fspecificaTion: FSPECIFICATION, // 物料规格
      //     fvolumeUnit: FVOLUMEUNIT, // 尺寸单位
      //     funit: FBASEUNIT // 计价单位
      //   })
      // }
      if (ev.fmaterialId) {
        const item = this.tableData[this.tableIndex]
        item.fnumber = ev.fnumber
        item.fname = ev.fname
        item.fmaterialId = ev.fmaterialId
        item.fmodel = ev.fmodel
        item.funit = ev.fpurchasepriceUnit
        item.funitId = ev.fpurchasepriceUnitId
        item.fdescripTion = ev.fdescripTion
        item.fspecificaTion = ev.fspecificaTion
        if (this.oldfnumber !== ev.fnumber) {
          this.delArr.push(this.oldFid)
          this.oldfnumber = ''
        }
      }
      this.openMaterialDialog = false
    },
    // 打开物料编码
    async handleGetMateriel(row, index) {
      this.oldFid = this.tableData[index].fentryId
      this.oldfnumber = this.tableData[index].fnumber
      this.tableIndex = index
      this.openMaterialDialog = true
    },
    // 搜索
    handleMaterielSearch() {
      this.materielPagination.pageNum = 1
      this.handleGetMateriel()
    },
    // 含税选中
    handleTax() {
      const tableData = this.tableData[this.tableIndex]
      if (this.purchaseForm.fisIncludedTax) {
        // 单价不可输
        this.fpriceDisabled = true
        this.ftaxPriceDisabled = false
        // 上限
        tableData.fupprice = tableData.ftaxPrice
        // 下限
        tableData.fdownprice = tableData.ftaxPrice
      } else {
        this.ftaxPriceDisabled = true
        this.fpriceDisabled = false
        // 上限
        tableData.fupprice = tableData.ftaxPrice
        // 下限
        tableData.fdownprice = tableData.ftaxPrice
      }
    },
    // 单价
    handleUnitPrice(row) {
      const { fprice, ftaxRate } = row
      // 含税单价
      row.ftaxPrice = maxDecimal(fprice * (1 + ftaxRate / 100))
      // // 上限
      row.fupprice = row.ftaxPrice
      // // 下限
      row.fdownprice = row.ftaxPrice
    },
    // 含税单价
    handleTaxIncluded(row) {
      const { ftaxPrice, ftaxRate } = row
      row.fprice = ftaxPrice / (1 + ftaxRate / 100)
      // 上限
      row.fupprice = ftaxPrice
      // 下限
      row.fdownprice = ftaxPrice
    },
    // 税率影响
    handleTaxRate(row) {
      const { fprice, ftaxRate, ftaxPrice, fupprice, fdownprice } = row
      if (!this.fpriceDisabled) {
        row.ftaxPrice = fprice * (1 + ftaxRate / 100)
        row.fupprice = ftaxPrice
        row.fdownprice = ftaxPrice
        row.fupprice = fupprice.toFixed(2)
        row.fdownprice = fdownprice.toFixed(2)
      } else {
        row.fprice = ftaxPrice / (1 + ftaxRate / 100)
        row.fupprice = ftaxPrice
        row.fdownprice = ftaxPrice
        row.fupprice = fupprice.toFixed(2)
        row.fdownprice = fdownprice.toFixed(2)
      }
    },
    // 删除行数据
    deleteMateriel(index) {
      const item = this.tableData[index]
      if (item.fentryId) {
        const DATA = {
          EntryIds: [item.fentryId]
        }
        this.$confirm('确定要删除么？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          deletePurPriceDetails(DATA).then(res => {
            if (res.code === 0) {
              this.queryTPurPriceList()
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        })
      } else {
        this.tableData.splice(index, 1)
      }
    },
    jumpMateriel(FNUMBER, fisdefault) {
      if (fisdefault === 0) {
        this.$router.push({ path: `/oldetailMateriel/${FNUMBER}` })
      } else {
        this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
      }
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = {
        Numbers: [this.purchaseForm.code],
        remarks: this.remarks
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.isdanjuDialog = false
        this.getPriceList()
        if (this.appro === 1) {
          Bus.$emit('reload')
        }
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审批通过
    async audit(ev) {
      if (ev === 2) {
        const api = purUnAudit
        this.toExamineFun(api)
        return
      }
      this.remarks = ''
      this.isdanjuDialog = true
      this.appro = ev
    },
    // 同意不同意
    pushDownOrder() {
      const api = this.appro === 1 ? purAudit : purAuditUnApproval
      this.toExamineFun(api)
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? purSubmit : purAuSubmit
      this.toExamineFun(api)
    },
    // 禁用
    async using(ev) {
      const api = ev === 1 ? disablePur : undisablePur
      this.toExamineFun(api)
    },
    // 删除
    async editPurchase() {
      if (this.isDisabled) {
        this.$confirm('请先反审核后再删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$confirm('确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePur({ Numbers: [this.purchaseForm.code] }).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/purchasePriceList' })
        })
      })
    },
    // 套打
    queryReportForm1(ev) {
      const fbi = this.purchaseForm.code
      if (ev === 1) {
        this.$router.push({ path: `/purchasePriceTao1/${fbi}` })
      } else {
        this.$router.push({ path: `/purchasePriceLian1/${fbi}` })
      }
    },
    // 新增行
    newLine() {
      const DATA = {
        fnote: '',
        fmaterialId: '', // 物料编码
        fprice: 0, // 单价
        fentryId: 0,
        ftaxPrice: 0, // 含税单价
        fupprice: 0, // 价格上限
        fdownprice: 0, // 价格下限
        feffectiveDate: new Date(), // 生效时间
        fexpiryDate: '2100-01-01', // 失效时间
        ftaxRate: this.ftaxRate || 0, // 税率
        fdescripTion: '', // 描述
        fmodel: '', // 物料规格
        fvolumeUnit: '', // 尺寸单位
        FBASEUNIT: '' // 计价单位
      }
      this.tableData.push(DATA)
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      this.tableData.map((res, index) => {
        const row = this.tableData[index]
        if (index >= this.subscript) {
          res[this.property] = item
          if (this.property === 'fprice') {
            this.handleUnitPrice(row)
          } else if (this.property === 'ftaxPrice') {
            this.handleTaxIncluded(row)
          }
        }
      })
    },
    // 删除行
    delHang() {
      this.deleteMateriel(this.indexSelf)
    },
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.editPurchasePrice {
  @include listBom;
  padding: 10px;
  display: flex;
  flex-direction: column;
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.5vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left:0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .header-name {
    position: relative;
    margin-bottom: 15px;
    .search {
      margin-left: 250px;
    }
    .newBtn {
      transform: translateY(6px);
    }
    .btn {
      margin-left: 480px;
      transform: translateY(8px);
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .layout {
    display: flex;
    flex-direction: column;
    .header {
      margin-bottom: 10px;
      margin-top: -5px;
    }

    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 20%;
        min-width: 238px;
        margin-bottom: 5px;
        .input-width {
          min-width: 138px !important;
        }
      }
    }
  }
}

.el-input__icon {
  cursor: pointer;
}

.icon-jin-rud-ao-bo {
  cursor: pointer;

  &:hover {
    color: #409eff;
  }
}

.materiel-form {
  display: flex;
  align-items: center;
  flex-direction: row;
  margin-bottom: 20px;
  position: relative;

  .btn {
    transform: translateY(18%);
    margin-left: 450px !important;
  }
  .confirm {
    transform: translateY(18%);
  }
  .materiel-code {
    font-weight: bold;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
  }

  .input-width {
    width: 185px;
    margin-right: 10px;
  }
}
.dialogClass ::v-deep .el-dialog__body {
  padding: 0 20px;
}
</style>
